package LinkList;

/**
 * 栈，先进后出
 *
 * @author Delouch
 * @date 2024-10-17 16:39:46
 */

public class Stack<E> {

    private DoubleLinkNode<E> top;

    private int size;

    public void pop(E element) {
        DoubleLinkNode node = new DoubleLinkNode(this.top, element, null);
        if (top == null) {
            top = node;
        }else {
            top.nextNode = node;
            top = node;
        }
        this.size += 1;
    }

    public E push() {
        if (top == null) {
            return null;
        }
        this.size -= 1;
        E pushValue = this.top.value;
        DoubleLinkNode<E> preNode = this.top.prevNode;
        this.top = preNode;
        if (this.top != null) {
            this.top.nextNode = null;
        }
        return pushValue;
    }

    public E top() {
        if (this.top == null) {
            return null;
        }
        return this.top.value;
    }

    public int size() {
        return this.size;
    }

    public boolean isEmpty() {
        return this.size > 0 ? false : true;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        DoubleLinkNode node = this.top;
        while (node != null) {
            sb.append(node.value).append("  --  ");
            node = node.prevNode;
        }
        return sb.append("\n").toString();
    }
}
